package com.zero.manage.web.utils;

import cn.hutool.core.util.IdUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author zero
 * 文件上传工具类
 */
public class FileUtil {

    /**
     * 相对路径保存
     */
    public static final String RELATIVE_PATH = "/file/";

    /**
     * 上传文件
     *
     * @param file 文件对象
     */
    public static String uploadFile(MultipartFile file) {
        String fileName = null;
        try {
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            fileName = IdUtil.simpleUUID() + "-" + originalFilename;
            File dest = new File(RELATIVE_PATH + fileName);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
//            file.transferTo(dest);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;

    }

    /**
     * 文件下载
     *
     * @param res
     * @param fileName 要下载的文件名
     * @return
     */
    public static void download(HttpServletResponse res, String fileName) {
        //响应头设置
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        try {
            res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] buff = new byte[1024];
        try (OutputStream os = res.getOutputStream();
             FileInputStream fileInputStream = new FileInputStream(new File(RELATIVE_PATH + fileName));
             BufferedInputStream bis = new BufferedInputStream(fileInputStream)) {

            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除单个文件
     */
    public static void delFile(String fileName) {
        File file = new File(RELATIVE_PATH + fileName);
        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }
}
